var curDeviceId;
var curIccid;
var flow_table = {

	"iDisplayLength" : 10,
	"processing" : true,
	"serverSide" : true,
	"paging" : true,
	"lengthChange" : false,
	"searching" : false,
	"ordering" : false,
	"info" : true,
	"autoWidth" : false,
	"oLanguage" : {
		"sProcessing" : "正在加载中......",
		// "sLengthMenu" : "每页显示 _MENU_ 条记录",
		"sZeroRecords" : "对不起，查询不到相关数据！",
		"sEmptyTable" : "暂无设备数据存在！",
		"sInfo" : "当前有共 _TOTAL_ 条设备记录",
		"sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
		"sSearch" : "搜索",
		"oPaginate" : {
			"sFirst" : "首页",
			"sPrevious" : "上一页",
			"sNext" : "下一页",
			"sLast" : "末页"
		}
	},
	columns : [
			{
				"data" : "device_id"
			},
			{
				"data" : "code"
			},
			{
				"data" : "plane_code"
			},
			{
				"data" : "value",
				render : function(data, type, full) {

					if (data > 0) {
						return (data / 1024 / 1024).toFixed(2) + 'M';
					} else {
						return '0M';
					}
				}
			},
			{
				"data" : "warncount",
				render : function(data, type, full) {
					if (data > 0) {

						return '<lable style="color:#F00000">有流量告警，已触发告警'
								+ data + '次</lable>';
					} else {
						return '<lable style="color:#006633">无流量告警</lable>';
					}
				}
			},
			{
				"data" : {
					"device_id" : "device_id",
					"code" : "code"
				},
				render : function(data, type, full) {
					if (data != null) {
						return '<lable style="color:#0066CC">'
								+ '  <a onclick="showHis('
								+ data.device_id
								+ ',\''
								+ data.code
								+ '\')"  href="#hisRecord" ><i class="fa fa-table"></i>流量历史查看</a></label>';
					} else {
						return '-';
					}
				}
			} ]
};

initTable = function() {
	console.log(1);
	var urlTmp = "/flow/loadFlow";
	flow_table.ajax = urlTmp;
	$('#flow_table').DataTable(flow_table);
	$('#flow_table').on('xhr.dt', function(e, settings, json, xhr) {
		initCharts(json.data[0].device_id, json.data[0].code);
		curDeviceId = json.data[0].device_id;
		curIccid = json.data[0].code;
	});
}

queryFlowDatas = function() {
	var url = "/flow/loadFlow?1=1";
	var params = '';
	var data = {};
	var form = document.getElementById("queryForm_flow"); // $('#queryForm');
	if (form.iccid.value != null && form.iccid.value != '') {
		// console.log(form.iccid.value);
		data.iccid = form.iccid.value;
	}
	if (form.planeCode.value != null && form.planeCode.value != '') {
		data.planeCode = form.planeCode.value;
	}
	flow_table.ajax = {
		"url" : url,
		"data" : data
	};
	console.log(flow_table.ajax);
	$('#flow_table').dataTable().api().destroy();
	$('#flow_table').DataTable(flow_table);

}

resetFlowForm = function() {
	var form = document.getElementById("queryForm_flow");
	form.iccid.value = null;
	form.planeCode.value = null;
}



initCharts = function(deviceId, iccid) {
	require.config({
		paths : {
			echarts : '//cdn.bootcss.com/echarts/2.2.7'
		}
	});
	require([ 'echarts', 'echarts/chart/line', 'echarts/chart/pie',
			'echarts/chart/bar' ], function(ec) {
		echarts = ec;
		DAY_FLOW = createDayFlow('flow_day', deviceId);
		MONTH_FLOW = createMonthFlow('flow_month', deviceId);
		$(window).resize(function() {
			DAY_FLOW.resize();
			MONTH_FLOW.resize();
		});
	});

	$('#hisRecord').text('3G卡(' + iccid + ')历史流量记录');
}


showHis = function(deviceId, iccid) {
	if(deviceId !=null){
		curDeviceId = deviceId;
	}
	if(iccid != null){
		curIccid = iccid;
	}
	loadDayFlow(curDeviceId);
	loadMonthFlow(curDeviceId);
	$('#hisRecord').text('3G卡(' + curIccid + ')历史流量记录');
}

createDayFlow = function(divId, deviceId) {
	var dom = document.getElementById(divId);
	DAY_FLOW = echarts.init(dom);
	loadDayFlow(deviceId);
	return DAY_FLOW;

}

loadDayFlow = function(deviceId) {// 按小时统计
	DAY_FLOW.clear();
	DAY_FLOW.hideLoading();
	var option = {
		color : [ '#00a1ff', '#ffae00' ],
		title : {
			text : '本月3G卡日流量',
			x : 'left'
		},
		legend : {
			x : 'right',
			y : '30',
			data : [ '3G卡日流量' ],
			textStyle : {
				color : '#666',
				fontWeight : 'bolder',
				fontSize : 10,
				fontFamily : 'Helvetica, Hiragino Sans GB, Microsoft Yahei, 微软雅黑, Arial, sans-serif'
			}
		},
		tooltip : {
			trigger : 'item',
			formatter : function(params) {
				var date = new Date(params.value[0]);
				data = date.getFullYear() + '-' + (date.getMonth() + 1) + '-'
						+ date.getDate() + ' ' + date.getHours() + '时'
						+ date.getMinutes() + '分';
				return data + '<br/>流量：' + params.value[1];
			}

		},
		noDataLoadingOption : {
			text : '暂无数据',
			effect : 'bubble',
			effectOption : {
				effect : {
					n : 0
				}
			},
			textStyle : {
				fontSize : 24,
				fontWeight : 'bold'
			}
		},
		// calculable : true,
		grid : {
			y : 50,
			y2 : 80,
			x : 60,
			x2 : 25
		},
		dataZoom : {
			show : true,
			start : 0
		},
		xAxis : [ {
			type : 'time'
		} ],
		yAxis : [ {
			type : 'value',
			axisLabel : {
				formatter : '{value}MB',
				textStyle : {
					color : '#666',
					fontSize : 8
				}
			}
		} ],
		series : [ {
			name : '3G卡日流量',
			type : 'line',
			smooth : true,
			showAllSymbol : true,
			itemStyle : {
				normal : {
					areaStyle : {
						type : 'default'
					}
				}
			},

			data : [],

		} ]
	};

	var time = (new Date()).format('yyyy-MM-dd 00:00:00');
	$
			.ajax({
				url : "/flow/loadDayFlow",
				async : true,
				data : {
					"deviceId" : deviceId,
					"createTime" : time
				},
				success : function(data) {
					// x轴
					if (data != null && data.length > 0) {

						var values = [];
						for (var i = 1; i < data.length; i++) {
							var tmp = []
							tmp.push(new Date(data[i]['create_time']));
							tmp
									.push((Number(data[i]['value'] / 1024 / 1024) - Number(data[i - 1]['value'] / 1024 / 1024))
											.toFixed(2));
							values.push(tmp);
						}

						option.series[0].data = values;
					}
					DAY_FLOW.setOption(option, true);
					// DP_GL_FLOW.hideLoading();

					// setTimeout(MainPage_Flow.loadFlow , mp_refresh_time);
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					console.log('exception>>' + textStatus);
					// setTimeout(MainPage_Flow.loadFlow , mp_refresh_time);
				}
			});

}

createMonthFlow = function(divId, deviceId) {
	var dom = document.getElementById(divId);
	MONTH_FLOW = echarts.init(dom);
	loadMonthFlow(deviceId);
	return MONTH_FLOW;

}

loadMonthFlow = function(deviceId) {// 按小时统计
	MONTH_FLOW.clear();
	MONTH_FLOW.hideLoading();
	var option = {
		color : [ '#ffae00' ],
		title : {
			text : '3G每月历史用量',
			x : 'left'
		},
		tooltip : {
			trigger : 'item',
			formatter : function(params) {
				var date = new Date(params.value[0]);
				data = date.getFullYear() + '-' + (date.getMonth() + 1) + '月';
				return data + '<br/>流量：' + params.value[1] + 'M';
			}

		},
		legend : {
			x : 'right',
			y : '30',
			data : [ '3G每月用量' ],
			textStyle : {
				color : '#666',
				fontWeight : 'bolder',
				fontSize : 10,
				fontFamily : 'Helvetica, Hiragino Sans GB, Microsoft Yahei, 微软雅黑, Arial, sans-serif'
			}
		},
		noDataLoadingOption : {
			text : '暂无数据',
			effect : 'bubble',
			effectOption : {
				effect : {
					n : 0
				}
			},
			textStyle : {
				fontSize : 24,
				fontWeight : 'bold'
			}
		},
		// calculable : true,
		grid : {
			y : 50,
			y2 : 80,
			x : 60,
			x2 : 25
		},
		dataZoom : {
			show : true,
			start : 0
		},

		xAxis : [ {
			type : 'time'
		} ],
		yAxis : [ {
			type : 'value',
			axisLabel : {
				formatter : '{value}M',
				textStyle : {
					color : '#666',
					fontSize : 8
				}
			}
		} ],
		series : [ {
			name : '3G每月用量',
			type : 'line',
			smooth : true,
			showAllSymbol : true,
			itemStyle : {
				normal : {
					areaStyle : {
						type : 'default'
					}
				}
			},
			data : []
		} ]
	};

	var time = (new Date()).format('yyyy-01-01 00:00:00');
	$.ajax({
		url : "/flow/loadMonthFlow",
		async : true,
		data : {
			"deviceId" : deviceId,
			"createTime" : time
		},
		success : function(data) {
			// x轴
			if (data != null && data.length > 0) {
				var values = [];
				for (var i = 0; i < data.length; i++) {
					var tmp = []
					tmp.push(new Date(data[i]['p_month']));
					tmp.push(Number(data[i]['p_value'] / 1024 / 1024)
							.toFixed(2));
					values.push(tmp);
				}

				option.series[0].data = values;
			}
			MONTH_FLOW.setOption(option, true);

		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			console.log('exception>>' + textStatus);
			// setTimeout(MainPage_Flow.loadFlow , mp_refresh_time);
		}
	});

}